package com.java.module.system.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.java.common.config.ProjectConfig;
import com.java.common.constant.Constants;
import com.java.common.utils.WebKit;
import com.java.common.utils.file.FileUploadUtils;
import com.java.module.system.service.ISysUeditorService;

/**
 * Ueditor 服务实现
 * 
 * @author yilabao
 * @date 2021年2月24日
 */
@Service
public class SysUeditorServiceImpl implements ISysUeditorService {

    private static final Logger LOG = LoggerFactory.getLogger(SysUeditorServiceImpl.class);

    private final String CONFIG_JSON_PATH = "json/ueditor.config.json";

    /**
     * Ueditor action 业务处理
     */
    @Override
    public String action(HttpServletRequest request) {

        String action = request.getParameter("action");

        if (Objects.equals(action, Action.CONFIG)) {
            return getConfig();
        }

        if (!Objects.equals(action, Action.UPLOADIMAGE)) {
            return renderState("action error.");
        }

        return upload(request);

    }

    /**
     * 图片上传
     * 
     * @author yilabao
     * @date 2021年2月24日
     * @param request
     * @return String
     */
    private String upload(HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = ((MultipartHttpServletRequest) request);

        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();

        MultipartFile file = multiFileMap.getFirst("upfile");

        if (file == null) {
            return renderState("upfile error");
        }

        String filePath = ProjectConfig.getUploadPath() + "/ueditor";

        String fileName = null;

        try {
            fileName = FileUploadUtils.upload(filePath, file);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

        String originalFilename = file.getOriginalFilename();

        String extName = FilenameUtils.getExtension(originalFilename);

        JSONObject ret = new JSONObject();

        ret.put("state", "SUCCESS");
        ret.put("url", fileName);
        ret.put("title", "");
        ret.put("original", originalFilename);
        ret.put("type", extName);
        ret.put("size", file.getSize());

        return ret.toJSONString();
    }

    /**
     * 获取Ueditor配置信息config.json
     * 
     * @author yilabao
     * @date 2021年2月24日
     * @return String
     */
    private String getConfig() {
        String json = null;
        try {
            Resource config = new ClassPathResource(CONFIG_JSON_PATH);
            json = IOUtils.toString(config.getInputStream(), Constants.UTF8);
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
        if (json == null) {
            return renderState("config.json configuration error.");
        }
        JSONObject jsonObj = JSON.parseObject(json);
        jsonObj.put("imageUrlPrefix", WebKit.getFileBasePath());
        return jsonObj.toJSONString();
    }

    /**
     * 生成Ueditor响应信息
     * 
     * @author yilabao
     * @date 2021年2月24日
     * @param state
     * @return String
     */
    private String renderState(String state) {
        JSONObject json = new JSONObject();
        json.put("state", state);
        return json.toJSONString();
    }

    /**
     * 接口action操作类型
     * 
     * @author yilabao
     * @date 2021年2月24日
     */
    private class Action {

        /**
         * 获取配置
         */
        public static final String CONFIG = "config";

        /**
         * 图片上传
         */
        public static final String UPLOADIMAGE = "uploadimage";

    }

}